package com.foreknow.elm.dao.impl;

import com.foreknow.elm.dao.UserDao;
import com.foreknow.elm.po.User;
import com.foreknow.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    private Connection con = null;
    private PreparedStatement pst = null;
    private ResultSet rs = null;
    private int isRight = 0;
    @Override
    public User dgetUserByIdByPass(String userId, String password) throws SQLException {
        User user = new User();
        String sql = "select * from user where userId=? and password =?";
        con = DBUtil.getConnection();
        try {
            pst = con.prepareStatement(sql);
            pst.setString(1,userId);
            pst.setString(2,password);
            rs = pst.executeQuery();
            while (rs.next()){
                user.setUserId(rs.getString("userId"));
                user.setPassword(rs.getString("password"));
                user.setUserName(rs.getString("userName"));
                user.setUserSex(rs.getInt("userSex"));
                user.setUserImg(rs.getString("userImg"));
                user.setDelTag(rs.getInt("delTag"));
            }
        } finally {
           DBUtil.close(rs,pst);
        }
        return user;
    }

    @Override
    public int dgetUserById(String userId) throws SQLException {
        User user = new User();
        int isRight = 0;
        String sql = "select * from user where userid=?";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setString(1,userId);
            rs = pst.executeQuery();
            while (rs.next()){
                user.setUserId(rs.getString("userId"));
            }
            if (user.getUserId() != null){
                isRight = 1;
            }
        }finally {
            DBUtil.close(rs,pst);
        }

        return isRight;
    }

    @Override
    public int dsaveUser(User user) throws SQLException {
        String sql = "insert into user(userid,password,username,usersex) values(?,?,?,?)";
        con = DBUtil.getConnection();
        try {
            pst = con.prepareStatement(sql);
            pst.setString(1,user.getUserId());
            pst.setString(2,user.getPassword());
            pst.setString(3,user.getUserName());
            pst.setInt(4,user.getUserSex());
            isRight = pst.executeUpdate();
        }finally {
            DBUtil.close(pst);
        }

        return isRight;
    }
}
